package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// TimeoutMiddleware 超时中间件
func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
		defer cancel()
		c.Request = c.Request.WithContext(ctx)
		finished := make(chan struct{})
		go func() {
			c.Next()
			close(finished)
		}()
		select {
		case <-finished:
			// 请求在超时时间内完成
		case <-ctx.Done():
			// 请求超时
			c.Writer.WriteHeader(http.StatusGatewayTimeout)
			c.Abort()
		}
	}
}
func main() {
	r := gin.Default()
	// 使用超时中间件，设置超时时间为5秒
	r.Use(TimeoutMiddleware(5 * time.Second))
	r.GET("/ping", func(c *gin.Context) {
		// 模拟长时间运行的处理
		time.Sleep(10 * time.Second)
		c.String(http.StatusOK, "pong")
	})
	r.Run(":8080")
}
